import requests
import time
from statistics import mean

def ping_test(url):
    try:
        start_time = time.time()
        requests.get(url, timeout=5)
        return (time.time() - start_time) * 1000
    except:
        return None

def download_speed_test(url):
    try:
        start_time = time.time()
        response = requests.get(url, timeout=10)
        download_time = time.time() - start_time
        file_size = len(response.content)
        speed = (file_size * 8) / (download_time * 1_000_000)  # 转换为 Mbps
        return speed
    except:
        return None

def test_speed():
    print("开始测试网络速度，请稍候...")
    
    # 测试服务器列表
    servers = [
        "http://speedtest.tele2.net/1MB.zip",
        "https://speed.hetzner.de/1GB.bin",
        "http://speedtest.ftp.otenet.gr/files/test1Mb.db",
        "http://speedtest.tokyo2.linode.com/100MB-tokyo.bin"
    ]
    
    # 测试延迟
    print("正在测试网络延迟...")
    ping_servers = [
        "http://www.baidu.com",
        "http://www.qq.com",
        "http://www.taobao.com"
    ]
    ping_results = []
    for server in ping_servers:
        result = ping_test(server)
        if result:
            ping_results.append(result)
    
    # 测试下载速度
    print("正在测试下载速度...")
    download_speeds = []
    for server in servers:
        speed = download_speed_test(server)
        if speed:
            download_speeds.append(speed)
    
    # 输出结果
    print("\n测试结果:")
    if ping_results:
        print(f"平均网络延迟: {mean(ping_results):.2f} ms")
    else:
        print("网络延迟测试失败")
        
    if download_speeds:
        print(f"平均下载速度: {mean(download_speeds):.2f} Mbps")
    else:
        print("下载速度测试失败")

if __name__ == "__main__":
    test_speed()